package cn.flying.base.security.service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.flying.base.common.constants.Constants;
import cn.flying.base.common.enums.RtCodeEnum;
import cn.flying.base.common.exception.BizException;
import cn.flying.base.core.common.utils.Ft;
import cn.flying.base.security.configuration.LoginUser;
import cn.flying.base.security.domain.SysLoginLog;
import cn.flying.base.security.domain.SysUser;
import cn.flying.base.security.domain.SysUserRole;
import cn.flying.base.security.mapper.SysUserMapper;
import cn.flying.base.security.utils.PasswordEncoderUtil;
import cn.flying.base.security.vo.UserPassInfo;


/**
 * @description: 系统用户服务
 * @author: lvyong
 * @date: 2023年05月24日 13:12
 * @version: 1.0
 */
@Service
public class SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysSeqService sysSeqService;
    @Resource
    private PasswordEncoderUtil passwordEncoderUtil;


    /**
     * 通过用户名查询用户
     *
     * @param username
     * @return
     */
    public LoginUser findUserByUsername(String username) {
        SysUser sysUser = sysUserMapper.findUserByUsername(username);
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(sysUser.getUserId());
        loginUser.setUsername(sysUser.getUsername());
        loginUser.setName(sysUser.getName());
        loginUser.setPassword(sysUser.getPassword());
        loginUser.setOrgId(sysUser.getOrgId());
        loginUser.setOrgName(sysUser.getOrgName());
        loginUser.setEmail(sysUser.getEmail());
        loginUser.setMobile(sysUser.getMobile());
        loginUser.setGender(sysUser.getGender());
        loginUser.setBirthday(sysUser.getBirthday());
        loginUser.setStatus(sysUser.getStatus());
        loginUser.setLocked(sysUser.getLocked());
        loginUser.setLastLoginTime(sysUser.getLastLoginTime());
        loginUser.setRemark(sysUser.getRemark());
        loginUser.setPicture(sysUser.getPicture());
        loginUser.setTenantId(sysUser.getTenantId());
        return loginUser;
    }

    /**
     * 通过用户ID查询用户角色权限
     *
     * @param userId
     * @return
     */
    public List<SysUserRole> getUserRoleList(String userId) {
        return sysUserMapper.getUserRoleList(userId);
    }

    /**
     * 更新用户的最后登录时间
     *
     * @param username
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateUserLoginTimeByUsername(String username) {
        sysUserMapper.updateUserLoginTimeByUsername(username);
    }

    /**
     * 注册用户
     *
     * @param user
     */
    @Transactional(rollbackFor = Exception.class)
    public void registerUser(SysUser user) {
        String encrypt = passwordEncoderUtil.encrypt(user.getPassword());
        user.setPassword(encrypt);
        user.setUserId(sysSeqService.getSeq("USER"));
        user.setStatus("Y");
        user.setLocked("N");
        user.setCreatedBy(user.getUsername());
        user.setCreatedTime(new Date());
        user.setUpdatedBy(user.getUsername());
        user.setUpdatedTime(new Date());
        user.setRevision(0L);
        sysUserMapper.insertUser(user);
    }

    /**
     * 修改用户密码
     *
     * @param info
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateUserPassword(UserPassInfo info) {
        SysUser sysUser = sysUserMapper.findUserByUserId(info.getUserId());
        boolean match = passwordEncoderUtil.match(info.getOldPassword(), sysUser.getPassword());
        if (!match) {
            throw new BizException("原密码不对，请重新输入！");
        }
        String encrypt = passwordEncoderUtil.encrypt(info.getNewPassword());
        sysUser.setPassword(encrypt);
        sysUser.setUpdatedBy((String) Ft.ThreadLocal.get(Constants.USER_NAME));
        sysUser.setUpdatedTime(new Date());
        sysUserMapper.updateUserPassword(sysUser);
    }

    /**
     * 查询通一时刻的login记录
     *
     * @param sysLoginLog
     * @return
     */
    public SysLoginLog findLoginLogByTime(SysLoginLog sysLoginLog) {
        return sysUserMapper.findLoginLogByTime(sysLoginLog);
    }

    /**
     * 保存登录日志
     *
     * @param loginLog
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertLoginLog(SysLoginLog loginLog) {
        loginLog.setId(Ft.Snowflake.genId());
        sysUserMapper.insertLoginLog(loginLog);
    }

    /**
     * 重置密码
     *
     * @param request
     */
    @Transactional(rollbackFor = Exception.class)
    public void restUserPassword(HttpServletRequest request) {
        String username = request.getParameter("username");
        String cellphone = request.getParameter("cellphone");
        String vercode = request.getParameter("vercode");
        String password = request.getParameter("password");

        SysUser sysUser = sysUserMapper.findUserByUsername(username);
        if (Objects.isNull(sysUser)) {
            throw new BizException(RtCodeEnum.R10001);
        }
        if (!cellphone.equals(sysUser.getMobile())) {
            throw new BizException(RtCodeEnum.R10016);
        }

        //TODO 校验验证码

        sysUser.setPassword(passwordEncoderUtil.encrypt(password));
        sysUserMapper.updateUserPassword(sysUser);
    }
}
